<template>
  <div class="app-container h-flex">
    <div v-loading="listLoading" class="tree-box app-container__left">
      <div class="type-title" @click="listQuery.pid='';search()">部门</div>
      <el-tree
        ref="tree_box"
        :data="cloneDeptTreeData"
        node-key="id"
        icon-class="el-icon-arrow-right"
        :expand-on-click-node="false"
        default-expand-all
        :props="defaultDeptProps"
        @node-click="nodeClick" />
    </div>
    <div
      ref="tree_box_right"
      class="h-flex-elastic v-flex overflow-hidden app-container__right">
      <filter-form :form="listQuery" :data="filterData" @search="search" @addForm="addForm">
        <el-upload
          style="display:inline-block;margin-left: 10px;"
          action="/dfs/upload"
          :show-file-list="false"
          :before-upload="beforeUpload">
          <el-button
            class="form__button icon-green"
            size="mini"
            type="success"
            icon="el-icon-upload2">
            导入
          </el-button>
        </el-upload>
      </filter-form>
      <div ref="main" class="v-flex-elastic">
        <el-table
          v-if="height>0"
          ref="multipleTable"
          v-loading="listLoading"
          :data="tableData"
          border
          row-key="id"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :height="height"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            label="序号"
            align="center"
            type="index"
            width="50" />
          <el-table-column
            prop="deptName"
            label="部门名称"
            show-overflow-tooltip
            width="200" />
          <el-table-column
            prop="deptCode"
            show-overflow-tooltip
            label="部门编号" />
          <el-table-column label="部门类型" show-overflow-tooltip>
            <template slot-scope="{row}">
              <span v-for="(item,index) in row.deptTypeNames" :key="item.id">
                {{ index>0?'，':'' }}{{ item.deptTypeName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="phone"
            show-overflow-tooltip
            label="部门电话" />
          <el-table-column
            prop="managerId"
            show-overflow-tooltip
            label="负责人" />
          <el-table-column
            label="启用"
            align="center"
            width="70">
            <template slot-scope="{row, $index}">
              <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="enable(row, $index)" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            fixed="right"
            align="center"
            width="210"
            class-name="small-padding fixed-width">
            <template slot-scope="{row ,$index}">
              <el-button
                v-permission-button="'ITPS-VIEW'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-view"
                @click="view(row)" />
              <el-button
                v-permission-button="'ITPS-UPDATE'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-edit"
                @click="updateForm(row,$index)" />
              <el-button
                v-permission-button="'ITPS-DELETE'"
                class="el-icon-defined"
                size="mini"
                icon="el-icon-delete"
                @click="deleteData(row,$index)" />
              <el-button
                size="mini"
                class="td-btn-operation"
                @click="site(row)">管辖区站</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <base-dialog
        class="department-dialog"
        :visible.sync="dialog.visible"
        :title="dialog.title"
        :loading="dialog.loading"
        :disabled="dialog.disabled"
        @open="beforeOpenDialog"
        @updateData="updateData">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          :disabled="dialog.disabled"
          label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="部门名称" prop="deptName">
                <el-input v-model="temp.deptName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="部门编号"
                prop="deptCode">
                <el-input
                  v-if="dialogStatus == 'update'"
                  v-model="temp.deptCode"
                  disabled />
                <el-input v-else v-model="temp.deptCode" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="上级部门" prop="parentId">
                <select-tree
                  ref="tree_box1"
                  v-model="temp.parentId"
                  :options="deptTreeData"
                  :props="defaultProps" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="部门类型"
                prop="deptTypeIds">
                <el-select
                  v-model="temp.deptTypeIds"
                  multiple>
                  <el-option
                    v-for="item in optionsDept"
                    :key="item.id"
                    :label="item.deptTypeName"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="部门电话"
                prop="phone">
                <el-input v-model="temp.phone" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="铁路类型"
                prop="railType">
                <el-select
                  v-model="temp.railType"
                  clearable>
                  <el-option
                    v-for="item in railTypeList"
                    :key="item.id"
                    :label="item.dicKey"
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="部门简称"
                prop="deptShortName">
                <el-input v-model="temp.deptShortName" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="负责人"
                prop="managerId">
                <el-input v-model="temp.managerId" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="排序号"
                prop="orderNum">
                <el-input v-model="temp.orderNum" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="启用">
                <el-switch v-model="temp.status" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </base-dialog>
      <!-- <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false">

        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="!disabled"
            type="primary"
            @click="dialogStatus==='create'?addData():updateData()">
            保存
          </el-button>
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
        </div>
      </el-dialog> -->
      <site
        ref="site"
        :dept-attr="deptAttr" />
    </div>
  </div>
</template>

<script>
import { getDeptTypes, getListAllTree, getList, saveOrUpdate, deleteById, upload } from '@/api/dsc/system/department'
import { getListByTypeCode } from '@/api/dsc/system/dictionary/general'
import { deepClone } from '@/utils'
import site from './components/Site.vue'
import { tableMixin } from '@/utils/public'
export default {
  name: 'DscDepartment',
  components: {
    site
  },
  mixins: [tableMixin],
  data() {
    return {
      // 部门树
      deptTreeData: [],
      cloneDeptTreeData: [],
      defaultDeptProps: {
        children: 'children',
        label: 'label'
      },
      // 数据默认字段
      defaultProps: {
        parent: 'parentId', // 父级唯一标识
        value: 'id', // 唯一标识
        label: 'label', // 标签显示
        children: 'children' // 子级
      },
      // 所属应用数据列表
      optionsApp: [],
      // 部门下拉选项
      optionsDept: [],
      railTypeList: [], // 铁路类型
      treeHeight: 0, // tree高度
      height: 0, // table高度
      tableData: [], // 表格数据
      listQuery: {// 搜索条件
        pid: '',
        keyName: '',
        deptTypeId: ''
      },
      filterData: {
        deptTypeId: {
          key: 'deptTypeId',
          type: 'select',
          title: '部门类型',
          placeholder: '所有部门类型',
          options: [],
          props: {
            label: 'deptTypeName',
            value: 'id'
          }
        },
        status: {
          key: 'status',
          type: 'select',
          title: '启用状态',
          placeholder: '启用状态',
          options: [
            { label: '启用', value: 1 },
            { label: '禁用', value: 0 }
          ]
        },
        keyName: {
          key: 'keyName',
          type: 'input',
          placeholder: '请输入部门名称'
        }
      },
      total: 0,
      textMap: {
        update: '编辑',
        view: '查看',
        create: '添加'
      },
      dialogFormVisible: false, // 弹窗开关
      dialogStatus: '', // 弹窗类型（添加、查看、编辑）
      dialog: {
        visible: false,
        title: '',
        loading: false,
        disabled: false
      },
      temp: {},
      tempForm: {// 弹窗表单
        id: null,
        deptName: '',
        deptCode: '',
        parentId: null,
        managerId: '',
        railType: '',
        deptShortName: '',
        deptTypeIds: [],
        phone: '',
        orderNum: '',
        status: 1
      },
      rowIndex: null,
      deptAttr: {}, // 当前行部门属性
      rowObj: null, // 行数据
      rules: {},
      rulesModel: {
        deptName: [{ required: true, message: '必填', trigger: 'blur' }, { max: 20, message: '小于20个字符', trigger: 'blur' }],
        deptCode: [{ required: true, message: '必填', trigger: 'blur' }, { max: 20, message: '小于20个字符', trigger: 'blur' }],
        deptTypeIds: [{ required: true, message: '必选', trigger: 'blur' }],
        managerId: [{ max: 20, message: '小于20个字符', trigger: 'blur' }],
        phone: [{ max: 20, message: '小于20个字符', trigger: 'blur' }]
      },
      listLoading: false,
      dialogSiteVisible: false,
      disabled: false, // 是否禁止表单操作
      multipleSelection: [] // 选择行的复选框
    }
  },
  created() {
    this.temp = Object.assign({}, this.tempForm)
    // 查询部门的
    getDeptTypes({}).then(response => {
      this.optionsDept = response.data
      this.filterData['deptTypeId'].options = response.data
      this.getListAllTree()
    })
    // 铁路类型
    getListByTypeCode({ typeCode: this.publicConfig['013'] }).then(response => {
      this.railTypeList = response.data
    })
  },
  methods: {
    closeSite() {
      this.dialogSiteVisible = false
    },
    // 管辖区站
    site(row) {
      this.deptAttr = {
        deptId: row.id,
        deptName: row.deptName,
        deptCode: row.deptCode,
        idPath: row.idPath,
        parentCode: row.parentCode
      }
      this.$refs.site.dialogFormVisible = true
    },
    // 查询部门树
    getListAllTree() {
      this.listLoading = true
      getListAllTree({}).then(response => {
        this.deptTreeData = response.data
        this.cloneDeptTreeData = deepClone(response.data)
        this.search()
      }).catch(_ => {
        this.listLoading = false
      })
    },
    // 查询列表
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.tableData = response.data
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 点击tree节点回调
    nodeClick(data) {
      this.listQuery.pid = data.id
      this.search()
    },
    // 搜索
    search() {
      // this.listQuery.page = 1
      this.getList()
    },
    beforeUpload(file) {
      const param = new FormData()
      param.append('file', file)
      console.log(param)
      upload(param).then(response => {
        this.getListAllTree()
        this.notifiySuccess('导入成功!')
      })
      return false
    },
    // 添加
    addForm() {
      // this.disabled = false
      this.temp = Object.assign({}, this.tempForm)
      this.setTreeDisable()
      // this.dialogStatus = 'create'
      // this.dialogFormVisible = true
      this.rules = Object.assign({}, this.rulesModel)
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '添加',
        loading: false,
        disabled: false
      })
    },
    // 添加数据
    // addData() {
    //   this.validate().then(() => {
    //     this.saveOrUpdate(this.temp, 1)
    //   })
    // },
    // 查看
    view(row) {
      // this.disabled = true
      this.temp = Object.assign({}, this.tempForm) // copy obj
      this.temp = Object.assign(this.temp, row) // copy obj
      // this.dialogStatus = 'view'
      this.rules = {}
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '查看',
        loading: false,
        disabled: true
      })
    },
    // 编辑
    updateForm(row, $index) {
      // this.disabled = false
      this.rowIndex = $index
      this.rowObj = row
      this.temp = Object.assign({}, this.tempForm) // copy obj
      this.temp = Object.assign(this.temp, row) // copy obj
      this.setTreeDisable()
      // this.dialogStatus = 'update'
      this.rules = Object.assign({}, this.rulesModel)
      // this.dialogFormVisible = true
      this.dialog = Object.assign({}, this.dialog, {
        visible: true,
        title: '编辑',
        loading: false,
        disabled: false
      })
    },
    setTreeDisable() {
      this.deptTreeData = deepClone(this.cloneDeptTreeData)
      if (!this.temp.id) return
      let data = [...this.deptTreeData]
      let current = []
      while (data.length || current.length) {
        if (data[0] && data[0].id === this.temp.id) {
          this.$set(data[0], 'disabled', true)
          current = [...data[0].children]
          data = []
        } else {
          if (current.length) {
            this.$set(current[0], 'disabled', true)
            current.push(...current[0].children)
            current.shift()
          } else {
            data.push(...data[0].children)
            data.shift()
          }
        }
      }
    },
    // 编辑数据
    updateData() {
      this.validate().then(() => {
        this.saveOrUpdate(this.temp, 2)
      })
    },
    // type 1 添加，2 编辑
    saveOrUpdate(params, type) {
      this.listLoading = true
      const param = Object.assign({}, params)
      saveOrUpdate(param).then(response => {
        if (this.dialog.title === '添加') {
          this.tableData.unshift(response.data)
          this.total++
          // 左侧树新增节点
          const [obj, id] = [{
            id: response.data.id,
            label: response.data.deptName,
            children: []
          }, response.data.parentId ? response.data.parentId : '']
          this.$refs.tree_box.append(obj, id)
          this.$refs.tree_box1.appendNode(obj, id)
        } else {
          Object.assign(this.rowObj, response.data)
          // 左侧树编辑节点
          this.$refs.tree_box.getNode(response.data.id).data.label = response.data.deptName
          if (this.$refs.tree_box1) {
            this.$refs.tree_box1.updateNode(response.data.id, response.data.deptName)
          }
        }
        this.notifiySuccess('保存成功')
        this.dialog.visible = false
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    beforeOpenDialog() {
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 删除
    deleteData(row, $index) {
      this.confirmBox('确定删除?').then(() => {
        deleteById(row.id).then(response => {
          this.notifiySuccess('删除成功!')
          // this.tableData.splice($index, 1)
          // this.total--
          this.$refs.tree_box.remove(row.id)
          if (this.$refs.tree_box1) this.$refs.tree_box1.removeNode(row.id)
          this.search()
        })
      }).catch(() => {

      })
    },
    // 启用、停用
    enable(row, $index) {
      this.rowObj = row
      this.rowIndex = $index
      this.saveOrUpdate(row, 2)
    },
    // 批量删除
    deleteBatch() {
      this.confirmBox('确定删除?').then(() => {
        this.notifiySuccess('删除成功!')
        this.search()
      }).catch(() => {

      })
    },
    // 选择行复选框
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    // 全选、反选
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>
<style scoped>
  .svg-import{
    font-size: 11px;
    margin-right: 9px;
  }
</style>
